package com.fw.util;

import java.util.ArrayList;
import java.util.List;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;

import com.fw.service.bean.SearchCriteriaBean;

public class PageRequestUtils {

    public static final PageRequest getPageRequest(SearchCriteriaBean<?> searchCriteriaBean) {
	PageRequest pageRequest = null;
	if (searchCriteriaBean != null && searchCriteriaBean.getPage() != null && searchCriteriaBean.getSize() != null) {
	    Sort sort = null;
	    if (searchCriteriaBean.getOrder1() != null || searchCriteriaBean.getOrder2() != null || searchCriteriaBean.getOrder3() != null
	    /*
	     * || searchCriteriaBean.getDirection1() != null || searchCriteriaBean.getDirection2() != null ||
	     * searchCriteriaBean.getDirection3() != null
	     */
	    ) {

		List<Order> orders = new ArrayList<Order>();
		if (searchCriteriaBean.getOrder1() != null && searchCriteriaBean.getDirection1() != null) {
		    orders.add(new Order(PageRequestUtils.getDerection(searchCriteriaBean.getDirection1()), searchCriteriaBean.getOrder1()));
		}
		if (searchCriteriaBean.getOrder2() != null && searchCriteriaBean.getDirection2() != null) {
		    orders.add(new Order(PageRequestUtils.getDerection(searchCriteriaBean.getDirection2()), searchCriteriaBean.getOrder2()));
		}
		if (searchCriteriaBean.getOrder3() != null && searchCriteriaBean.getDirection3() != null) {
		    orders.add(new Order(PageRequestUtils.getDerection(searchCriteriaBean.getDirection3()), searchCriteriaBean.getOrder3()));
		}
		sort = new Sort(orders);
	    }

	    pageRequest = new PageRequest(searchCriteriaBean.getPage() - 1, searchCriteriaBean.getSize(), sort);
	}
	return pageRequest;
    }

    public static final Direction getDerection(String direction) {
	Direction result = null;
	if (direction == null || direction.isEmpty()) {
	    result = Direction.ASC;
	} else if (SearchCriteriaBean.DIRECTION_ASC.equals(direction)) {
	    result = Direction.ASC;
	} else if (SearchCriteriaBean.DIRECTION_DESC.equals(direction)) {
	    result = Direction.DESC;
	}
	return result;
    }
}
